package com.hzhr.iot.collect.protocol.logger;

import com.hzhr.iot.collect.Global;
import com.hzhr.iot.collect.constant.MessageFieldKeyEnum;
import com.hzhr.iot.collect.constant.RequestResponseFlagEnum;
import com.hzhr.iot.collect.constant.TransferDirEnum;
import com.hzhr.iot.collect.constant.UpDownEnum;
import com.hzhr.iot.collect.model.collectLog.CollectLogPostModel;
import com.hzhr.iot.collect.protocol.parser.Parser;
import com.hzhr.iot.collect.protocol.util.MessageUtil;
import com.hzhr.iot.collect.service.helper.CollectLogServiceHelper;
import com.hzhr.iot.collect.util.StrUtil;
import com.hzhr.iot.core.util.HzhrJsonUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.sdk.model.collectDevice.CollectDeviceModel;
import com.hzhr.iot.device.sdk.model.iotDevice.IotDeviceModel;
import com.hzhr.iot.device.sdk.service.Device_CollectDeviceService;
import com.hzhr.iot.device.sdk.service.Device_IotDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class Logger1 implements Logger{
    @Autowired
    CollectLogServiceHelper collectLogServiceHelper;
    @Autowired
    Device_IotDeviceService device_iotDeviceService;
    @Autowired
    Device_CollectDeviceService device_collectDeviceService;
    @Autowired
    Global global;
    @Autowired
    MessageUtil messageUtil;

    @Override
    public void log(Integer protocolId, String deviceId, String message, Parser parser, UpDownEnum upDownFlag) throws Exception {
        Map<MessageFieldKeyEnum, Object> messageObj = parser.parsing(message, protocolId, deviceId, upDownFlag);

        String reqMeterNo = HzhrTypeUtil.object2string(messageObj.get(MessageFieldKeyEnum.REQ_METER_NO));
        String respMeterNo = HzhrTypeUtil.object2string(messageObj.get(MessageFieldKeyEnum.RESP_METER_NO));
        String iotDeviceCode = HzhrTypeUtil.object2string(messageObj.get(MessageFieldKeyEnum.IOT_DEVICE_ID));
        String functionCode = HzhrTypeUtil.object2string(messageObj.get(MessageFieldKeyEnum.FUNCTION_CODE));
        String transDir = HzhrTypeUtil.object2string(messageObj.get(MessageFieldKeyEnum.TRANSFER_DIR));//传送方向
        String reqRespFlag = HzhrTypeUtil.object2string(messageObj.get(MessageFieldKeyEnum.REQ_RESP_FLAG));//请求响应标志
        String messageId = HzhrTypeUtil.object2string(messageObj.get(MessageFieldKeyEnum.MESSAGE_ID));//报文编号
        String controlCode = HzhrTypeUtil.object2string(messageObj.get(MessageFieldKeyEnum.CONTROL_CODE));//控制码
        String starteFlag = null;
        String transFlag = null;
        if (!StringUtils.isEmpty(controlCode)) {
            String controlCodeBin = StrUtil.decimal2binary(Integer.parseInt(controlCode));
            starteFlag = controlCodeBin.charAt(0) + ""; //通信发启标识：0 服务器端发启 1 设备端发启
            transFlag = controlCodeBin.charAt(1) + ""; //传输方向标识：0 下行 1 上行
        }

        if (StringUtils.isEmpty(transDir)) {//如果传送方向为空，则从控制码中获取
            if ("0".equals(starteFlag)) {
                transDir = TransferDirEnum.SERVER_BEGIN.getIdForMessage() + "";
            } else if ("1".equals(starteFlag)) {
                transDir = TransferDirEnum.DEVICE_BEGIN.getIdForMessage() + "";
            }
        }
        if (StringUtils.isEmpty(reqRespFlag)) {//如果请求响应标志为空，则从控制码中获取
            if (starteFlag.equals(transFlag)) {
                reqRespFlag = RequestResponseFlagEnum.REQ.getIdForMessage() + "";
            } else {
                reqRespFlag = RequestResponseFlagEnum.RESP.getIdForMessage() + "";
            }
        }

        if (deviceId != null) {
            //查询物联网设备
            String token = global.getFirstToken();
            Map<String, String> header = new HashMap<>();
            header.put("token", token);
            Map<String, Object> query = new HashMap<>();
            query.put("_show", "one");
            query.put("_show_info", true);
            query.put("_equal_iotPlatformDeviceId", deviceId);
            IotDeviceModel iotDeviceModel = null;
            try {
                iotDeviceModel = device_iotDeviceService.get(header, query).getModel();
            } catch (Exception e) {
                e.printStackTrace();
            }

            //写入采集日志
            if (iotDeviceModel != null) {
                CollectLogPostModel collectLogPostModel = new CollectLogPostModel();
                collectLogPostModel.setMessageId(iotDeviceCode + messageId);
                collectLogPostModel.setProtocalId(protocolId);
                collectLogPostModel.setFunctionCode(functionCode);
                collectLogPostModel.setIotDeviceId(iotDeviceModel.getId());
                collectLogPostModel.setIotDeviceCode(iotDeviceCode);
                collectLogPostModel.setIotDeviceImei(iotDeviceModel.getIotPlatformImei());
                collectLogPostModel.setStartTime(new Date().getTime());

                String meterNo = !StringUtils.isEmpty(reqMeterNo) ? reqMeterNo : respMeterNo;
                if (!StringUtils.isEmpty(meterNo)) {
                    String token1 = global.getFirstToken();
                    Map<String, String> header1 = new HashMap<>();
                    header1.put("token", token1);
                    Map<String, Object> query1 = new HashMap<>();
                    query1.put("_show", "one");
                    query1.put("_equal_code", meterNo);
                    query1.put("_equal_iotDeviceId", iotDeviceModel.getId());
                    CollectDeviceModel collectDeviceModel = device_collectDeviceService.get(header1, query1).getModel();
                    if (collectDeviceModel != null) {
                        collectLogPostModel.setCollectDeviceId(collectDeviceModel.getId());
                    }
                }

                if ("0".equals(transDir)) {
                    collectLogPostModel.setStarter(1);
                } else if ("1".equals(transDir)) {
                    collectLogPostModel.setStarter(2);
                }

                if ("0".equals(reqRespFlag)) {
                    collectLogPostModel.setType(1);
                } else if ("1".equals(reqRespFlag)) {
                    collectLogPostModel.setType(2);
                }

                collectLogPostModel.setMessage(message);

                Map<String, Object> messageObjTmp = new HashMap<>();
                for (Map.Entry<MessageFieldKeyEnum, Object> entry :
                messageObj.entrySet()) {
                    messageObjTmp.put(entry.getKey().getName(), entry.getValue());
                }
                collectLogPostModel.setMessageObj(HzhrJsonUtil.object2json(messageObjTmp));

                try {
                    collectLogServiceHelper.post(collectLogPostModel);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
